﻿using System.Web.WebPages;
using WebMatrix.Data;
    
namespace WishlistUtilities {
    public static class ListLookupUtility {
        public static int LookupListId(string username, string listSlug) {
            var wishlistId = -1;    // use a value of -1 to indicate a failed list lookup

            var db = Database.Open("wishlistdb");

            // lookup the user; need to convert the slug replacement char w/ an underscore (SQL wildcard character)
            username = username.Replace(SlugUtility.SLUGREPLACEMENTCHAR, '_');
            var user = db.QuerySingle("SELECT Id, DefaultListId FROM WishlistUser WHERE Username LIKE @0", username);

            if (user != null) {
                // lookup the wishlist if a slug is provided
                if (!listSlug.IsEmpty()) {
                    var wishlist = db.QuerySingle("SELECT Id FROM List WHERE WishlistUserId = @0 AND Slug = @1", user.Id, listSlug);
                    wishlistId = (wishlist != null) ? wishlist.Id : -1;
                } else {
                    //No list ID or slug was provided, so display that user's default list
                    var wishlist = db.QuerySingle("SELECT Id FROM List WHERE Id = @0", user.DefaultListId);
                    wishlistId = (wishlist != null) ? wishlist.Id : -1;
                }
            }

            return wishlistId;
        }
    }
}